import os
from pathlib import Path
from app.libs.enums import RType
from app.libs.exception import APIException
from app.libs.forms import UploadByPathForm
from app.libs.utils import HttpHelper
from app.ro import CreateRemoteDirParam, UploadPureVideoParam
from app.vo import FailChapterVO, FailVideoVO
from .base import BaseService
import filetype
class ChapterService(BaseService):
   
    @classmethod
    def upload(cls, chapter_dir, vsConfig: dict,  course_id=None, course_name=None) -> FailChapterVO:
        chapter_dir = Path(chapter_dir)
        def createRemoteDir():
            # 创建文件夹 获取 章节 id
            chapter_name = os.path.basename(chapter_dir)
            param = CreateRemoteDirParam().set_attrs(dict(
                name = chapter_name,
                type = RType.CHAPTER.value,
                course_id = course_id
            ))
            # 发起请求
            url = '/v1/resource/create/pure'
            resp = HttpHelper.post(url, param) 
            # 获取返回结果中的内容
            chapter_id = resp.content_object['id']
            chapter_name = resp.content_object['name']
            return chapter_id, chapter_name
        chapter_id, chapter_name = createRemoteDir()
        # 获取下面的视频, 组装上传
        video_paths = chapter_dir.glob('*')
        video_paths = [ v_path for v_path in video_paths
            if os.path.isfile(v_path) and filetype.is_video(v_path)]
        
        fail_chapter = FailChapterVO(dict(
            name=chapter_name,
            dir=chapter_dir,
            belong_course= course_name,
            fail_videos = []
        )) # 记录上传失败的

        # 开始上传, @WAIT可以使用多线程
        for v_path in video_paths:    
            up_param = UploadPureVideoParam().set_attrs(vsConfig)
            up_param.set_attrs(dict(
                chapter_id=chapter_id,
                course_id=course_id,
                type=1
            )) # 准备参数
            res = cls.uploadVideo(param=up_param,file=(v_path.name, open(v_path, mode='rb')) )
            if res: # 记录失败的记录
                fail_chapter.fail_videos.append(FailVideoVO(
                dict(
                    name=v_path.name,
                    dir=v_path
                )
                ))
        return fail_chapter
        
    
    @classmethod
    def upload_by_path(cls, form: UploadByPathForm) -> FailChapterVO:
        return cls.upload(
            form.path.data,
            vsConfig=form.vsConfigForm.data)
        


    @classmethod
    def uploadVideo(cls, param: UploadPureVideoParam, file):
        """ 上传视频
            url: http://127.0.0.1:5000/v1/resource/upload
        """
        url = '/v1/resource/upload'
        
        try: 
            resp =  HttpHelper.post(url=url, params=param, files={'file': file})
            return None # 代表成功
        except APIException as e:
            return e.msg
       

 